//
//  ComposeViewController.swift
//  Weibo
//
//  Created by 张远文 on 16/5/9.
//  Copyright © 2016年 张远文. All rights reserved.
//

import UIKit
import SVProgressHUD

class ComposeViewController: UIViewController {

    private lazy var keyBoardView: EmoticonKeyBoardView = EmoticonKeyBoardView {[weak self] (em) -> () in
        self?.textView.insertAttrText(em)
    }
    
    //监听方法
    
    @objc private func selectPicture() {
        selectorVC.view.snp_updateConstraints { (make) in
            make.height.equalTo(224 + 80 + 40)
        }
    }
    
    @objc private func selectEmoticon() {
        
        //如果是默认键盘 键盘的inputView 是nil
        
        //取消第一响应者
        textView.resignFirstResponder()
        //设置输入视图
        textView.inputView = (textView.inputView == nil ? keyBoardView : nil)
        //成为第一响应者
        textView.becomeFirstResponder()
    }
    
    //关闭按钮监听方法
    @objc private func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //发布微博按钮监听方法
    @objc private func send() {
        guard let token = UserAccountViewModel().token else {
            SVProgressHUD.showErrorWithStatus("客官,没有登录不能发微博哦")
            return
        }
        
        let parmaters = ["access_token": token,"status":textView.fulltext()]
        
        if selectorVC.imageList.count >= 1 {
            //图文微博
            let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
            //print(selectorVC.imageList[0])
            let imageData = UIImagePNGRepresentation(selectorVC.imageList[0])
            
            NetworkTools.sharedTools.uploadImage(urlString, parmaters: parmaters, imageData: imageData!, finished: { (result, error) in
                if error != nil {
                    SVProgressHUD.showErrorWithStatus("发布微博失败")
                    print("图文微博:")
                    print(error)
                    return
                }
                SVProgressHUD.showSuccessWithStatus("发布图文微博成功")
                self.dismissViewControllerAnimated(true, completion: nil)
            })
            
        } else {
            //文字微博
            let urlString = "2/statuses/update.json"
            NetworkTools.sharedTools.requestJsonDict(.POST, urlString: urlString, parmaters: parmaters) { (result, error) in
                if error != nil {
                    SVProgressHUD.showErrorWithStatus("发布微博失败")
                    return
                }
                SVProgressHUD.showSuccessWithStatus("发布微博成功")
                self.dismissViewControllerAnimated(true, completion: nil)
            }
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        view.backgroundColor = UIColor.whiteColor()
        setupUI()
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        textView.becomeFirstResponder()
    }
    
    private func setupUI() {
        //设置导航条
        setNavBar()
        //设置文本框
        setupTextView()
        setupToolBar()
        //添加图片选择控制器
        setSelectorView()
        //注册通知
        registerNotification()
    }
    
    private func setSelectorView() {
        //添加子视图控制器
        addChildViewController(selectorVC)
        //添加子视图
        view.addSubview(selectorVC.view)
        //调整视图层次结构
        view.bringSubviewToFront(toolBar)
        selectorVC.view.snp_makeConstraints { (make) in
            make.left.bottom.right.equalTo(view)
            make.height.equalTo(0)
        }
    }
    
    private func registerNotification() {
        //添加通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(keyboardWillChange), name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    //移除通知
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    //通知监听方法
    @objc private func keyboardWillChange(noti: NSNotification) {
        print(noti)
        //获取动画时间
        let duration = noti.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! Double
        let rect = (noti.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        
        //修改toolbar约束
        //获取键盘高度
        let offset = -screenH + rect.origin.y
        toolBar.snp_updateConstraints { (make) in
            make.bottom.equalTo(offset)
        }
        UIView.animateWithDuration(duration) { 
            //强制刷新
            self.view.layoutIfNeeded()
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    
    //MARK: - 懒加载控件
    private lazy var textView: EmoticonTextView = {
       
        let tv = EmoticonTextView()
        tv.delegate = self
        tv.font = UIFont.systemFontOfSize(18)
        tv.textColor = UIColor.darkGrayColor()
        //设置键盘消失模式
        tv.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        //设置弹簧效果开启
        tv.alwaysBounceVertical = true
        
        return tv
    }()
    
    private lazy var placeHolderLabel: UILabel = UILabel(title: "分享新鲜事...", size: 18, color: UIColor.lightGrayColor())
    
    private lazy var toolBar: UIToolbar = UIToolbar()
    
    //图片选择器
    private lazy var selectorVC: PictureSelectorCollectionViewController = PictureSelectorCollectionViewController()
    
}

extension ComposeViewController: UITextViewDelegate {
    
    func textViewDidChangeSelection(textView: UITextView) {
        //设置占位文本隐藏
        placeHolderLabel.hidden = textView.hasText()
        //设置发布按钮交互
        self.navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
}

//设置UI
extension ComposeViewController {
    
    //设置工具条
    private func setupToolBar() {
        view.addSubview(toolBar)
        
        //设置约束
        toolBar.snp_makeConstraints { (make) in
            make.left.bottom.right.equalTo(view)
            make.height.equalTo(40)
        }
        
        //设置按钮以及点击事件
        var items = [UIBarButtonItem]()
        
        //添加 UIBarButtonItem
        let itemSettings = [["imageName": "compose_toolbar_picture","actionName": "selectPicture"],
                             ["imageName": "compose_mentionbutton_background"],
                             ["imageName": "compose_trendbutton_background"],
                             ["imageName": "compose_emoticonbutton_background","actionName": "selectEmoticon"],
                             ["imageName": "compose_add_background"]]
        
        for dict in itemSettings {
            let item = UIBarButtonItem(imageName: dict["imageName"]!, target: self, actionName: dict["actionName"])
            
            items.append(item)
            
            let space = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
            
            items.append(space)
            
        }
        //删除最后一个弹簧
        items.removeLast()
        
        toolBar.items = items
        
    }
    
    private func setupTextView() {
        //添加子视图
        view.addSubview(textView)
        
        //设置约束
        textView.snp_makeConstraints { (make) in
            make.top.left.right.equalTo(self.view)
            make.height.equalTo(view.bounds.height / 3)
        }
        
        //添加占位文本
        textView.addSubview(placeHolderLabel)
        placeHolderLabel.snp_makeConstraints { (make) in
            make.top.equalTo(textView.snp_top).offset(8)
            make.left.equalTo(textView.snp_left).offset(5)
        }
    }
    
    private func setNavBar() {
        //添加两侧按钮
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: #selector(close))
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: .Plain, target: self, action: #selector(send))
        self.navigationItem.rightBarButtonItem?.enabled = false
        
        //设置中心视图
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 40))
        navigationItem.titleView = titleView
        
        //添加导航栏 发布信息的UIlabel
        let titleLabel = UILabel(title: "发微博", size: 17, color: UIColor.darkGrayColor())
        let nameLabel = UILabel(title: UserAccountViewModel().userName ?? "", size: 14, color: UIColor.lightGrayColor())
        //添加子视图
        titleView.addSubview(titleLabel)
        titleLabel.addSubview(nameLabel)
        
        //设置约束
        titleLabel.snp_makeConstraints { (make) in
            make.top.equalTo(titleView.snp_top)
            make.centerX.equalTo(titleView.snp_centerX)
        }
        nameLabel.snp_makeConstraints { (make) in
            make.bottom.equalTo(titleView.snp_bottom)
            make.centerX.equalTo(titleView.snp_centerX)
        }
        
    }
}
